package com.glkj.vipsystem.modules.merchant.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.glkj.vipsystem.common.utils.PageUtils;
import com.glkj.vipsystem.common.utils.Query;
import com.glkj.vipsystem.common.utils.R;
import com.glkj.vipsystem.common.validator.ValidatorUtils;
import com.glkj.vipsystem.common.validator.group.AddGroup;
import com.glkj.vipsystem.common.validator.group.UpdateGroup;
import com.glkj.vipsystem.entity.ao.CompanyAO;
import com.glkj.vipsystem.entity.ao.ShopAO;
import com.glkj.vipsystem.entity.gen.Company;
import com.glkj.vipsystem.modules.sys.controller.AbstractController;
import com.glkj.vipsystem.service.ICompanyService;
import com.glkj.vipsystem.service.IShopService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

/**
 * 公司店铺控制器
 *
 * @author LiMuchan
 */
@RestController
@RequestMapping("/merchant/shop")
public class ShopController extends AbstractController {

    @Resource
    private IShopService shopService;
    @Resource
    private ICompanyService companyService;

    /**
     * 列表
     */
    @RequestMapping(value = "/list")
    @RequiresPermissions({"merchant:shop:list"})
    public R list(@RequestParam Map<String, Object> params) {
        String shopName = (String) params.get("shopName");
        String companyId = (String) params.get("companyId");
        Wrapper<ShopAO> wrapper = new EntityWrapper<ShopAO>();
        wrapper.setSqlSelect("*,(SELECT company_name FROM t_company WHERE id = t_shop.company_id) as company_name" +
                ",(select count(*) from t_employee where shop_id = t_shop.id) as employee_num");
        wrapper.orderBy("id desc");
        // 数据权限控制
        if (isCompanyRole()) {
            // 公司管理员
            String username = getUser().getUsername();
            wrapper.where("company_id = (select id from t_company where `username` = '" + username + "')");
        } else if (StringUtils.isNotBlank(companyId)) {
            wrapper.eq("company_id", companyId);
        }
        if (StringUtils.isNotBlank(shopName)) {
            wrapper.like("shop_name", shopName);
        }
        Page<ShopAO> page = shopService.selectPage(
                new Query<ShopAO>(params).getPage(),
                wrapper
        );
        return R.ok().put("page", new PageUtils(page));
    }

    /**
     * 详情
     */
    @RequestMapping(value = "/detail/{id}")
    @RequiresPermissions({"merchant:shop:list"})
    public R detail(@PathVariable("id") Integer id) {
        return R.ok().put("item", shopService.selectById(id));
    }

    /**
     * 保存新增
     */
    @RequestMapping(value = "/save")
    @RequiresPermissions({"merchant:shop:save"})
    public R save(@RequestBody ShopAO shop) {
        ValidatorUtils.validateEntity(shop, AddGroup.class);
        shop.setStatus(1);
        shop.setCreateTime(new Date());
        try {
            shopService.save(shop);
        } catch (DuplicateKeyException e) {
            return R.error("同公司下店铺名称重复");
        }
        return R.ok();
    }


    /**
     * 修改
     */
    @RequestMapping(value = "/update")
    @RequiresPermissions({"merchant:shop:update"})
    public R update(@RequestBody ShopAO shop) {
        ValidatorUtils.validateEntity(shop, UpdateGroup.class);
        try {
            shopService.updateById(shop);
        } catch (DuplicateKeyException e) {
            return R.error("同公司下店铺名称重复");
        }
        return R.ok();
    }

    /**
     * 修改状态
     */
    @RequestMapping(value = "/updateStatus")
    @RequiresPermissions({"merchant:shop:update"})
    public R updateStatus(@RequestBody ShopAO shop) {
        shopService.updateById(shop);
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping(value = "/delete")
    @RequiresPermissions({"merchant:shop:delete"})
    public R delete(@RequestBody Integer[] ids) {
        if (ids != null && ids.length > 0) {
            shopService.deleteBatch(Arrays.asList(ids));
        }
        return R.ok();
    }

    /**
     * 获取公司店铺
     */
    @RequestMapping(value = "/getByCompany")
    public R getByCompany(@RequestParam("companyId") Integer companyId) {
        if (companyId == null) {
            return R.ok().put("data", new ArrayList<>());
        }
        Wrapper<ShopAO> wrapper = new EntityWrapper<ShopAO>();
        wrapper.orderBy("id desc");
        // 数据权限
        if (isCompanyRole()) {
            // 公司管理员
            String username = getUser().getUsername();
            wrapper.where("company_id = (select id from t_company where `username` = '" + username + "')");
        } else if (isEmployeeRole()) {
            // 店铺员工
            String username = getUser().getUsername();
            wrapper.where("id = (select shop_id from t_employee where `username` = '" + username + "')");
        } else {
            wrapper.eq("company_id", companyId);
        }
        List<ShopAO> shopAOS = shopService.selectList(
                wrapper
        );
        return R.ok().put("data", shopAOS);
    }

    /**
     * 获取公司店铺树
     */
    @RequestMapping(value = "/getCompanyShopTree")
    public R getCompanyShopTree() {
        List<Map<String, Object>> data = new ArrayList<>();
        // 首先获取公司
        Wrapper<CompanyAO> wrapper = new EntityWrapper<>();
        wrapper.orderBy("id desc");
        String username = getUser().getUsername();

        Wrapper<ShopAO> shopAOWrapper = new EntityWrapper<>();
        shopAOWrapper.orderBy("id desc");

        // 公司管理员
        if (isCompanyRole()) {
            wrapper.eq("username", username);
            shopAOWrapper.where("company_id = (select id from t_company where `username` = '" + username + "')");
        } else if (isEmployeeRole()) {
            // 当前登录用户为员工
            wrapper.where("id = (select company_id from t_employee where username = '" + username + "')");
            shopAOWrapper.where("id = (select shop_id from t_employee where `username` = '" + username + "')");
        }
        List<CompanyAO> companyAOS = new ArrayList<>(companyService.selectList(wrapper));
        if (!CollectionUtils.isEmpty(companyAOS)) {
            // 获取公司下的店铺
            List<ShopAO> shopAOS = shopService.selectList(shopAOWrapper);
            companyAOS.forEach(companyAO -> {
                Map<String, Object> company = new HashMap<>();
                company.put("id", companyAO.getId());
                company.put("name", companyAO.getCompanyName());
                List<Map<String, Object>> children = new ArrayList<>();
                Iterator<ShopAO> shopIt = shopAOS.iterator();
                while (shopIt.hasNext()) {
                    ShopAO shopAO = shopIt.next();
                    if (shopAO.getCompanyId().equals(companyAO.getId())) {
                        Map<String, Object> shop = new HashMap<>();
                        shop.put("id", shopAO.getId());
                        shop.put("name", shopAO.getShopName());
                        children.add(shop);
                        shopIt.remove();
                    }
                }
                if(!children.isEmpty()){
                    company.put("children", children);
                }
                data.add(company);
            });
        }

        return R.ok().put("data", data);
    }
}
